package com.link.base.ext.autocfg.controller;


import com.link.base.user.model.CoreUser;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.base.ext.autocfg.model.AutoCfg;
import com.link.base.ext.autocfg.service.AutoCfgService;
import com.link.core.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字段扩展配置模块，头信息对象
 * @author 姚润发
 * @date 2017/07
 */
@Controller("AutoCfgController")
@RequestMapping("/link/autoCfg")
public class AutoCfgController extends BasicController<AutoCfg> {

    private static final Logger logger = LogManager.getLogger(AutoCfgController.class);

    @Resource
    private AutoCfgService autoCfgService;

    @Override
    public BasicService<AutoCfg> getBasicService() throws Exception {
        return autoCfgService;
    }

    /**
     * 根据条件查询记录,默认分页(若将'pageFlag'设置为'false'，则不分页)
     */
    @RequestMapping(value = "/queryAutoCfgByExamplePage")
    @ResponseBody
    public Map<String, Object> queryAutoCfgByExamplePage(QueryParams qps, AutoCfg entity, HttpSession session,
                                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            AutoCfg autoCfg = (AutoCfg) AutoCfg.transformClass(entity, qps);
            beforQueryAllOrExample(autoCfg, request);
            beforQueryExample(autoCfg, request);
            autoCfg.setUnionStandardCorp(0L);//联合查询标准账套下的数据
            List<AutoCfg> list = getBasicService().queryByExamplePage(autoCfg);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((AutoCfg) autoCfg, list.size()));
        } catch (Exception e) {
            logger.error("AutoCfgController捕获异常: ",e);
            result.put("success", false);
            result.put("rows", new ArrayList<AutoCfg>());
            result.put("result", e.getMessage());
            if (e instanceof BasicServiceException) {
                result.put("detailMessage", ((BasicServiceException) e).getDetailMessage());
            }
        }
        return result;
    }

    /**
     * 导出
     */
    @Override
    @RequestMapping(value = "/queryAutoCfgByExamplePage/exportData")
    @ResponseBody
    public Map<String, Object> exportData(AutoCfg entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        logger.info("导出配置对象列表...");
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter;
            String exportType = "xlsx";
            CoreUser user = UserUtil.getUser();
            if (null != user) {
                user.setExportType(qps.getExportFileType());
            }
            if (exportType.equals(user.getExportType())) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            AutoCfg autoCfg = (AutoCfg) BasicModel.transformClass(entity, qps);
            while (!qps.getStopExport()) {

                beforQueryAllOrExample(autoCfg, request);
                beforQueryExample(autoCfg, request);
                autoCfg.setUnionStandardCorp(0L);
                List<AutoCfg> list = getBasicService().queryByExamplePage(autoCfg);
                if (qps.getPage() == 1) {
                    qps.setTotal(autoCfg.getTotal());
                }
                exportWriter.wirteData(list);
                autoCfg.setPage(qps.getPage());
                autoCfg.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            logger.error("AutoCfgController捕获异常: ",e);
            result.put("success", false);
            result.put("result", e.getMessage());
            if (e instanceof BasicServiceException) {
                result.put("detailMessage", ((BasicServiceException) e).getDetailMessage());
            }
        }
        return result;
    }

}
